﻿using Builder;

string rootPath = "";   //根路径地址 //执行的命令列表
string sln = "";    //sln文件名称
DirectoryInfo dir = new DirectoryInfo( "."); //路径为当前文件所在路径
rootPath = dir.FullName;
//查找sln文件
var slnFile = dir.GetFiles().FirstOrDefault(x => x.Extension == ".sln");

if (slnFile == null)
{
    Console.WriteLine("同级目录下未找到sln文件");
    return;
}

List<string> lstCmd = new List<string>(){$"cd {rootPath}&"};

sln = slnFile.Name;
//递归遍历当前目录查找所有项目文件并依据目录构建命令列表
SearchCsprojFile(dir);
//合成革单条命令
string cmdAll = $"cd {rootPath}&";
cmdAll = lstCmd.Aggregate(cmdAll, (current, cmd) => current + (cmd + "&"));
cmdAll += "exit";
//执行并输出
CmdHelper.RunCmd(cmdAll);
// Console.WriteLine(outStr);

Console.WriteLine("按任意键结束。。。。");
Console.ReadKey();

/*
 * 递归遍历当前目录查找所有项目文件并依据目录构建命令列表
 *      dir为目录路径
 *      key为项目解决方案文件夹路径
*/
void SearchCsprojFile(DirectoryInfo dir, string key = "")
{
    //遍历所有文件查找项目文件
    foreach (var file in dir.GetFiles())
    {
        if (file.Extension == ".csproj")
        {
            string path = key.TrimStart('/');
            string folder = path.Substring(0, path.LastIndexOf("/")).Replace("/", "\\");
            string cmd = $"dotnet sln {sln} add {path}/{file.Name} " +
                         $"--solution-folder {folder}";
            lstCmd.Add(cmd);
        }
    }
    //递归所有子文件夹
    foreach (var childDir in dir.GetDirectories())
    {
        SearchCsprojFile(childDir, key + "/" + childDir.Name + "");
    }
}